package com.sunsharing.utils;

import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import lombok.extern.log4j.Log4j;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j
public class XmlUtilTemp {


    /**
     * 解析Xml
     */
    public Map parseToMap(Element node, String nodeName, String className) {
        String sourceName = nodeName;
        Map<String, Object> xmlMap = new HashMap();
        Map sourceMap = new HashMap();
        try {
            Class clazz = Class.forName("com.sunsharing.entity." + className);
            Object obj = clazz.newInstance();

            List<Element> elements = null;
            Element chileNode = node.element(nodeName);
            if (chileNode == null) {
                elements = node.elements();
            } else {
                elements = chileNode.elements();
            }
            for (Element e : elements) {
                if ("".equals(e.getTextTrim())) {
                    String attributeValue = e.attributeValue("name");
                    if (StringUtils.isNullOrEmpty(attributeValue)) {
                        sourceMap.putAll(parseToMap(e, e.getName(), className));
                    } else {
                        sourceMap.putAll(parseToMap(e, attributeValue, className));
                    }
                } else {
                    xmlMap.put(e.getName(), e.getTextTrim());
                    log.info(e.getName() + ":::::" + e.getTextTrim());
                }
            }
            if (!xmlMap.isEmpty()) {
                sourceMap.put(sourceName, JSON.parseObject(JSON.toJSONString(xmlMap), obj.getClass()));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            log.info("没有找到【" + className + "】对应的类");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
            log.info("实例化【" + className + "】失败");
        }
        return sourceMap;
    }
}
